import type { SignInReq, UserResult } from "@/api/types";
import { defineStore } from "pinia";
import { ref } from "vue";
import { authApi } from "@/api";
import { userStorage } from "@/config/storage";
import { resetRouter } from "@/router/utils";
import { removeToken, setLoginInfo, setToken, setUserDept } from "@/utils/auth";
import { usePermissionStore } from "./permission";

/** 当前用户账号相关信息 */
export const useUserStore = defineStore("user", () => {
    /** 头像 */
    const avatar = ref(userStorage.value?.avatar || "");
    function SET_AVATAR(value: string): void {
        avatar.value = value;
    }

    /** 用户名 */
    const username = ref(userStorage.value?.username || "");
    function SET_USERNAME(value: string): void {
        username.value = value;
    }

    /** 昵称 */
    const nickname = ref(userStorage.value?.nickname || "");
    function SET_NICKNAME(value: string): void {
        nickname.value = value;
    }

    /** 页面级别权限 */
    const roles = ref<Array<string>>(userStorage.value?.roles || []);
    function SET_ROLES(value: Array<string>): void {
        roles.value = value;
    }

    /** 所属部门id */
    const deptId = ref(userStorage.value?.deptId || "");
    function SET_DEPT_ID(value: string): void {
        deptId.value = value;
    }

    /** 判断登录页面显示哪个组件（0：登录（默认）、1：手机登录、2：二维码登录、3：注册、4：忘记密码） */
    const currentPage = ref(0);
    function SET_CURRENT_PAGE(value: number): void {
        currentPage.value = value;
    }

    /** 是否勾选了登录页的免登录 */
    const isRemembered = ref(false);
    function SET_IS_REMEMBERED(bool: boolean): void {
        isRemembered.value = bool;
    }

    /** 登录页的免登录存储几天，默认7天 */
    const loginDay = ref(7);
    function SET_LOGIN_DAY(value: number): void {
        loginDay.value = value;
    }

    /** 创建人 */
    const createdBy = ref(userStorage.value?.createdBy || "");
    function SET_CREATED_BY(value: string): void {
        createdBy.value = value;
    }

    /** 创建时间 */
    const createdAt = ref(userStorage.value?.createdAt || "");
    function SET_CREATED_AT(value: string): void {
        createdAt.value = value;
    }

    /** 更新人 */
    const updatedBy = ref(userStorage.value?.updatedBy || "");
    function SET_UPDATED_BY(value: string): void {
        updatedBy.value = value;
    }

    /** 更新时间 */
    const updatedAt = ref(userStorage.value?.updatedAt || "");
    function SET_UPDATED_AT(value: string): void {
        updatedAt.value = value;
    }

    /** 账号密码登录 */
    async function loginByUserName(data: SignInReq): Promise<Resp<UserResult>> {
        // Note[登录流程] 点击按钮登录后调用登录接口
        return new Promise((resolve, reject) => {
            authApi.signInByUsername(data)
                .then((resp) => {
                    // Note[登录流程] 设置token和用户信息
                    if (ok(resp)) {
                        setToken(resp.data);
                        setLoginInfo(resp.data);
                        setUserDept(resp.data.deptId);
                    }
                    resolve(resp);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    /** 前端登出（不调用接口） */
    function logout(): void {
        username.value = "";
        roles.value = [];
        usePermissionStore().clearPermissions();
        resetRouter();
        removeToken(true);
    }

    return {
        avatar,
        SET_AVATAR,
        username,
        SET_USERNAME,
        nickname,
        SET_NICKNAME,
        roles,
        SET_ROLES,
        deptId,
        SET_DEPT_ID,
        currentPage,
        SET_CURRENT_PAGE,
        isRemembered,
        SET_IS_REMEMBERED,
        loginDay,
        SET_LOGIN_DAY,
        createdBy,
        SET_CREATED_BY,
        createdAt,
        SET_CREATED_AT,
        updatedBy,
        SET_UPDATED_BY,
        updatedAt,
        SET_UPDATED_AT,
        loginByUserName,
        logout,
    };
});
